<template>
  <div class="app-container">
    <div class="handle-content">
      <span class="right">
        <el-button type="primary" class="btn btn-sm btn-light me-2" @click="downloadTemplate">
          下载模版
        </el-button>
        <el-button type="primary" class="btn btn-sm btn-outline-light" @click="showInstructions = !showInstructions">
          使用说明
        </el-button>
      </span>
      <el-upload
        class="upload-demo"
        ref="upload"
        :action="url"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
        :before-remove="beforeRemove"
        multiple
        :limit="1"
        :on-exceed="handleExceed"
        :file-list="fileList"
        :auto-upload="false">
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
        <div slot="tip" class="el-upload__tip">只能上传xls与xlsx文件，且不超过10M</div>
      </el-upload>
    </div>

    

    <div v-if="showInstructions" class="card mt-4 shadow-sm">
      <div class="card-header bg-light d-flex justify-content-between align-items-center">
        <h6 class="mb-0">导入说明</h6>
      </div>

      <el-table
      :data="tableData"
      style="width: 100%">
      <el-table-column
        prop="a"
        label="列名"
        width="180">
      </el-table-column>
      <el-table-column
        prop="b"
        label="说明"
        width="180">
      </el-table-column>
      <el-table-column
        prop="c"
        label="必填">
      </el-table-column>
      <el-table-column
        prop="d"
        label="示例">
      </el-table-column>
      </el-table>
      <div class="card-body">
        <h6 class="mt-4 fw-bold">注意事项：</h6>
        <ul class="list-group list-group-flush">
          <li class="list-group-item">
            <i class="bi bi-check-circle text-success me-2"></i>
            一级用户的推荐人(根用户)手机号留空将自动关联到根用户
          </li>
          <li class="list-group-item">
            <i class="bi bi-check-circle text-success me-2"></i>
            根用户必须在系统中已存在
          </li>
          <li class="list-group-item">
            <i class="bi bi-check-circle text-success me-2"></i>
            同一推荐人下的用户按优先级排序
          </li>
          <li class="list-group-item">
            <i class="bi bi-check-circle text-success me-2"></i>
            导入过程中会自动计算用户层级，根用户层级为0，后续推荐用户层级依次递增
          </li>
        </ul>
        
        <div class="alert alert-info mt-4">
          <i class="bi bi-lightbulb me-2"></i>
          <strong>提示：</strong> 下载模板文件可以确保Excel格式正确
        </div>
      </div>
    </div>
    <!-- 导入结果 -->
    <div v-if="importResult" class="card mt-4 shadow-sm">
      <div class="card-header bg-light d-flex justify-content-between align-items-center">
        <h6 class="mb-0"><i class="bi bi-clipboard-data me-2"></i>导入结果统计</h6>
      </div>
      <div class="card-body">
        <div class="row">
          <div class="col-md-3 mb-3">
            <div class="card border-success h-100">
              <div class="card-body text-center p-3">
                <div class="text-success mb-2">
                  <i class="bi bi-check-circle-fill fs-1"></i>
                </div>
                <h2 class="text-success mb-1">{{ importResult.result.success_count }}</h2>
                <p class="mb-0 fw-medium">成功导入</p>
              </div>
            </div>
          </div>
          
          <div class="col-md-3 mb-3">
            <div class="card border-warning h-100">
              <div class="card-body text-center p-3">
                <div class="text-warning mb-2">
                  <i class="bi bi-skip-forward-circle-fill fs-1"></i>
                </div>
                <h2 class="text-warning mb-1">{{ importResult.result.skipped_count }}</h2>
                <p class="mb-0 fw-medium">已存在跳过</p>
              </div>
            </div>
          </div>
          
          <div class="col-md-3 mb-3">
            <div class="card border-danger h-100">
              <div class="card-body text-center p-3">
                <div class="text-danger mb-2">
                  <i class="bi bi-x-circle-fill fs-1"></i>
                </div>
                <h2 class="text-danger mb-1">{{ importResult.result.failed_count }}</h2>
                <p class="mb-0 fw-medium">导入失败</p>
              </div>
            </div>
          </div>
          
          <div class="col-md-3 mb-3">
            <div class="card border-primary h-100">
              <div class="card-body text-center p-3">
                <div class="text-primary mb-2">
                  <i class="bi bi-diagram-3-fill fs-1"></i>
                </div>
                <h2 class="text-primary mb-1">
                  {{ importResult.result.success_count + importResult.result.skipped_count }}
                </h2>
                <p class="mb-0 fw-medium">总用户数</p>
              </div>
            </div>
          </div>
        </div>
    </div>
    <!-- 失败记录 -->
    <div v-if="importResult.result.failed_count > 0" class="mt-4">
      <h6 class="fw-bold mb-3"><i class="bi bi-exclamation-triangle-fill text-danger me-2"></i>失败记录详情</h6>
      <div class="table-responsive">
        <table class="table table-bordered table-hover table-sm">
          <thead class="table-light">
            <tr>
              <th>行号</th>
              <th>手机号</th>
              <th>推荐人</th>
              <th>错误信息</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(row, index) in importResult.result.failed_rows" :key="index" class="align-middle">
              <td>{{ row.row }}</td>
              <td>
                <span v-if="row.phone">{{ row.phone }}</span>
                <span v-else class="text-muted fst-italic">(未提供)</span>
              </td>
              <td>
                <span v-if="row.recommender_phone">{{ row.recommender_phone }}</span>
                <span v-else class="text-muted fst-italic">(根用户)</span>
              </td>
              <td class="text-danger small">{{ row.error }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>
<script>
import { getImportUrl } from '@/api/member'
import { getToken } from '@/utils/auth' // get token from cookie

export default {

  data() {
    return {
      tableData: [{
            a: 'phone',
            b: '用户手机号',
            c: '是',
            d: '13800138001'
          }, {
             a: 'password',
            b: '登录密码',
            c: '是',
            d: 'secret123'
          }, {
             a: 'recommender_phone',
            b: '推荐人手机号（一级用户可留空）',
            c: '否',
            d: '13800138000'
          }, {
             a: 'priority',
            b: '优先级（数字越小越优先）',
            c: '否',
            d: '1'
          }],
      url:'',//导入路径
      fileList: [],
      showInstructions: true,
      importResult: null,
      exportPath: '',//导出路径
    }
  },
  mounted() {
    this.getImportUrl()
  },

  methods: {
    getImportUrl(){
        getImportUrl().then(response => {
        this.url = response.data.path + '?token=' + getToken()
        this.exportPath = response.data.exportpath + '?token=' + getToken()
      })
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      console.log(files)
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    handleSuccess(response, file, fileList){
      console.log('response:'+JSON.stringify(response, null, 2))
      console.log('file:'+JSON.stringify(file, null, 2))
      console.log('fileList:'+JSON.stringify(fileList, null, 2))
     
      if(response.code !== 20000)
      {
        this.$message.error(response.data.message)
        return 
      }
      this.importResult = response.data
      this.showInstructions = !this.showInstructions
      this.$message.success(response.data.message)
    },
    submitUpload() {
      if(this.fileList != []){
        this.$refs.upload.submit();
      }else{
        this.$message.warning('请选择上传文件')
      }
    },
    downloadTemplate(){
      const url = this.exportPath

      location.href = url
    }
  }

}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.app-container{
    .handle-content{
        margin: 1.5rem;
        .right{
            float: right;
            margin-bottom: 20px;
        }
    }
}
.table th {
  background-color: #f8f9fa;
}

.badge {
  font-weight: normal;
}

.list-group-item {
  padding: 0.75rem 1.25rem;
}
</style>
